package com.lagou.sqlsession;

import com.lagou.conf.Configuration;
import com.lagou.conf.MappedStatement;
import com.lagou.executor.Executor;
import com.lagou.executor.SimpleExecutor;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    private Executor executor;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new SimpleExecutor();
    }

    @Override
    public <E> List<E> selectList(String statement, Object... param) throws SQLException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statement);
        return executor.query(configuration, mappedStatement, param);
    }

    @Override
    public <T> T selectOne(String statement, Object... param) throws SQLException, IntrospectionException, NoSuchFieldException, InvocationTargetException, IllegalAccessException, InstantiationException {
        List<Object> objects = selectList(statement, param);
        if (objects != null && objects.size() > 1) {
            throw new RuntimeException("查询出多条数据");
        }
        return (T) selectList(statement, param).get(0);
    }

    @Override
    public int update(String statement, Object... param) throws SQLException, NoSuchFieldException, IllegalAccessException {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statement);
        return executor.update(configuration, mappedStatement, param);
    }

    @Override
    public int delete(String statement, Object... param) {
        return 0;
    }
}
